package com.example.nonameaa.service.AOP;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.example.nonameaa.entity.Logs;
import com.example.nonameaa.entity.User;
import com.example.nonameaa.service.LogsService;
import com.example.nonameaa.utils.AopLogs;
import com.example.nonameaa.utils.IpUtils;
import com.example.nonameaa.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 功能：
 * 作者：lhp
 * 日期：2024/10/6 10:22
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    @Resource
    LogsService logsService;

    @AfterReturning(pointcut = "@annotation(aopLogs)", returning = "jsonResult")
    public void recordLog(JoinPoint joinPoint, AopLogs aopLogs, Object jsonResult) {
        // 用户未登录的情况下  loginUser是null  是null的话我们就要从参数里面获取操作人信息
        User loginUser = TokenUtils.getCurrentUser();

        if(loginUser == null) {

            Object[] args = joinPoint.getArgs();
            if(ArrayUtil.isNotEmpty(args)) {
                if(args[0] instanceof User) {
                    loginUser = (User) args[0];
                }
            }
        }
        if(loginUser == null) {
            log.error("记录日志信息报错，未获取到当前操作用户信息");
            return;
        }
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 获取到请求的ip
        String ipAddr = IpUtils.getIpAddr(request);
        Logs logs = Logs.builder()
                .user(loginUser.getUsername())
                .operation(aopLogs.operation())
                .type(aopLogs.type().getValue())
                .ip(ipAddr)
                .time(DateUtil.now())
                .build();
        ThreadUtil.execAsync(() -> {
            // 异步记录日志信息
            logsService.save(logs);
        });

    }

}